
import UIKit

class MYGIndInfoDetailViewController: MYGBaseController {
    var id = 0
    var contentHeight = 100.0
    var isSubComment = false
    var currentCommentModel = MYGTopicCommentModel()
    var currentSection = 0
    var model = MYGInformationModel()
    var commentModels = [MYGTopicCommentModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "详情"
        initUI()
        requestData()
        
    }
    
    func requestData() {
        MYGLoading.show()
        self.table.isHidden = true
        let workingGroup = DispatchGroup()
        let workingQueue = DispatchQueue(label: "request_queue")
      
        workingGroup.enter()
        workingQueue.async {
            self.getDetailData {
                workingGroup.leave()
            }
        }
        workingGroup.enter()
        workingQueue.async {
            self.getCommentData {
                workingGroup.leave()
            }
        }
        workingGroup.notify(queue: workingQueue) {
            DispatchQueue.main.async {
                MYGLoading.hide()
                self.table.isHidden = false
                self.bindDetailData()
                self.table.reloadData()
            }
        }
    }
    
    private func initUI(){
        view.addSubview(writeImageV)
        writeImageV.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(SCALEWIDTH(13.5))
            make.bottom.equalToSuperview().offset(-bottomSafeheight - SCALEWIDTH(14.5))
            make.size.equalTo(CGSize(width: SCALEWIDTH(19), height: SCALEWIDTH(19)))
        }
        
        view.addSubview(starBtn)
        starBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-SCALEWIDTH(13.5))
            make.centerY.equalTo(writeImageV)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        view.addSubview(zanBtn)
        zanBtn.snp.makeConstraints { make in
            make.right.equalTo(starBtn.snp.left).offset(-10)
            make.centerY.equalTo(writeImageV)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        view.addSubview(shareBtn)
        shareBtn.snp.makeConstraints { make in
            make.right.equalTo(zanBtn.snp.left).offset(-10)
            make.centerY.equalTo(writeImageV)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        
        view.addSubview(writeTf)
        writeTf.snp.makeConstraints { make in
            make.right.equalTo(shareBtn.snp.left).offset(-SCALEWIDTH(10))
            make.left.equalTo(writeImageV.snp.right).offset(SCALEWIDTH(15))
            make.height.equalTo(SCALEWIDTH(25))
            make.centerY.equalTo(writeImageV)
        }
        view.addSubview(line)
        line.snp.makeConstraints { make in
            make.bottom.equalTo(writeImageV.snp.top).offset(-12)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        view.addSubview(table)
        table.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(line.snp.top)
        }
    }
    private lazy var table: UITableView = {
        let cont = UITableView(frame: CGRectZero, style: .grouped)
        cont.delegate = self
        cont.dataSource = self
        cont.separatorStyle = .none
        cont.backgroundColor = .clear
        if #available(iOS 15.0, *) {
            cont.sectionHeaderTopPadding = 0.0
            cont.sectionFooterHeight = 0.0
        }
        cont.register(UINib.init(nibName: "MYGCommentCountCell", bundle: nil), forCellReuseIdentifier: "MYGCommentCountCell")
        cont.register(cellWithClass: MYGTopicContentTableViewCell.self)
        cont.register(cellWithClass: MYGTopicCommentsTableViewCell.self)
        cont.showsVerticalScrollIndicator = false
        cont.rowHeight = UITableView.automaticDimension
        cont.tableHeaderView = UIView()
        cont.tableFooterView = UIView()
        return cont
    }()
    private lazy var writeImageV:UIImageView = {
       let cont = UIImageView()
        cont.image = UIImage.init(named: "MYG_topicDetail_edit")
        return cont
    }()
    private lazy var writeTf:UITextField = {
       let cont = UITextField()
        cont.placeholder = "写评论"
        cont.font = .medium(13)
        cont.delegate = self
        cont.returnKeyType = .send
        return cont
    }()
    private lazy var starBtn:UIButton = {
        let cont = UIButton()
        cont.setImage(UIImage.init(named: "MYG_topicDetail_collection"), for: .normal)
        cont.setImage(UIImage.init(named: "MYG_topicDetail_collectioned"), for: .selected)
        cont.addTarget(self, action: #selector(collectionOrNotYopic), for: .touchUpInside)
        return cont
    }()
    private lazy var zanBtn:UIButton = {
       let cont = UIButton()
        cont.setImage(UIImage.init(named: "MYG_topicDetail_like"), for: .normal)
        cont.setImage(UIImage.init(named: "MYG_topicDetail_liked"), for: .selected)
        cont.addTarget(self, action: #selector(likeOrNotTopic), for: .touchUpInside)
        return cont
    }()
    private lazy var shareBtn:UIButton = {
       let cont = UIButton()
        cont.setImage(UIImage.init(named: "MYG_topicDetail_share"), for: .normal)
        cont.addTarget(self, action: #selector(toShare), for: .touchUpInside)

        return cont
    }()
    
    var line: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#eeeeee")
        return control
    }()
    
    @objc func toShare() {
        
        let textToShare:String = "医路通"
        let imageToShare:UIImage = UIImage(named: "AppIcon")!
    
        let urlToShare:URL = URL(string: "\(shareUrl)/#/pages/news/newsDetail?id=\(id)")!

        let activityItems:Array = [textToShare, imageToShare, urlToShare] as [Any]
        let activityVC:UIActivityViewController = UIActivityViewController.init(activityItems: activityItems, applicationActivities: nil)
        activityVC.excludedActivityTypes = [UIActivity.ActivityType.postToFacebook,UIActivity.ActivityType.airDrop]

        navigationController?.present(activityVC, animated: true)
        
    }
    
    func getDetailData(completion:@escaping ()->Void) {
        MYGNetwork<MYGHomePageAPI, MYGInformationModel>.request(target: .informationDetail(param: [
            "id":"\(self.id)"
        ])) { item in
            self.model = item
            completion()
        } failed: { _, error in
            completion()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func getCommentData(completion:@escaping ()->Void) {
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGTopicCommentModel>>.request(target: .commentCommentList(param: [
            "data_id":self.id,"type":"6"
        ])) { item in
            self.commentModels = item.list
            completion()
        } failed: { _, error in
            completion()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func getAllReplyMoldes(replyArray:[MYGTopicCommentModel])->[MYGTopicCommentModel] {
        var result = [MYGTopicCommentModel]()
        for replyObject in replyArray {
            result.append(replyObject)
            if replyObject.reply?.count != 0 && replyObject.reply != nil{
                result.append(contentsOf: getAllReplyMoldes(replyArray:replyObject.reply!))
            }
        }
        return result
    }
    
    func bindDetailData() {
        self.zanBtn.isSelected = self.model.is_like == 1
        self.starBtn.isSelected = self.model.is_collect == 1
        self.table.reloadData()
    }
}
extension MYGIndInfoDetailViewController:UITextFieldDelegate{
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.text?.count ?? 0 > 0 {
            
            if self.isSubComment {
                sendSubComment(textField.text ?? "")
            }else {
                sendComment(textField.text ?? "")
            }
        }
        return true
    }
    func sendComment(_ text:String) {
        let params = ["content":text,"data_id":"\(self.model.id)","type":"6"]
        self.writeTf.text = ""
        self.writeTf.resignFirstResponder()
        MYGNetwork<MYGMeAPI, MYGTopicCommentModel>.request(target: .commentSubmit(param:params)) { item in
            let comment = item
            comment.reply = [MYGTopicCommentModel]()
            comment.doctor.name = MYGUserManager.getUser()?.doctor.name ?? ""
            comment.doctor.avatar = MYGUserManager.getUser()?.doctor.avatar ?? ""
            self.commentModels.append(comment)
            self.table.reloadData()
            NotificationCenter.default.post(name: Notification.Name("MYGIndInfoViewController_refresh"), object: nil)
//            let offsetY = max(0, self.table.contentSize.height - self.table.bounds.height)
//            self.table.setContentOffset(CGPoint(x: 0, y: offsetY), animated: true)
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func sendSubComment(_ text:String) {
        let params = ["content":text,"data_id":"\(self.model.id)","type":"6","pid":"\(self.currentCommentModel.id)"]
        self.writeTf.text = ""
        self.isSubComment = false
        self.writeTf.resignFirstResponder()
        MYGNetwork<MYGMeAPI, MYGTopicCommentModel>.request(target: .commentSubmit(param:params)) { item in
            let comment = item
            comment.reply = [MYGTopicCommentModel]()
            comment.doctor.name = MYGUserManager.getUser()?.doctor.name ?? ""
            comment.doctor.avatar = MYGUserManager.getUser()?.doctor.avatar ?? ""
            self.currentCommentModel.reply?.append(comment)
            self.table.reloadData()
            NotificationCenter.default.post(name: Notification.Name("MYGIndInfoViewController_refresh"), object: nil)
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    @objc func likeOrNotTopic() {
        var likeStatus = "1"
        if self.model.is_like == 0 {
            likeStatus = "1"
            self.model.is_like = 1
        }else {
            likeStatus = "0"
            self.model.is_like = 0
        }
        self.zanBtn.isSelected = self.model.is_like == 1
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .likeSubmit(param: [
            "id":"\(self.model.id)",
           "like_type":"6",
            "like_status":likeStatus])) { item in
                NotificationCenter.default.post(name: Notification.Name("MYGIndInfoViewController_refresh"), object: nil)
       } failed: { _, error in
           MMYGHUD.showToast(text: error)
       }
    }
    
    @objc func collectionOrNotYopic() {
        var collectionStatus = "1"
        if self.model.is_collect == 0 {
            collectionStatus = "1"
            self.model.is_collect = 1
        }else {
            collectionStatus = "0"
            self.model.is_collect = 0
        }
        self.starBtn.isSelected = self.model.is_collect == 1
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .collectSubmit(param: [
            "data_id":"\(self.model.id)",
           "type":"6",
            "collect_status":collectionStatus])) { item in

            } failed: { _, error in
           MMYGHUD.showToast(text: error)
       }
    }
}
extension MYGIndInfoDetailViewController:UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2 + self.commentModels.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 || section == 1{
            return 1
        }else{
            let child = self.commentModels[section - 2]
            if let replayArray = child.reply {
                return child.getAllReplyMoldes(replyArray: replayArray).count
            }
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section >= 2 {
            let model = self.commentModels[section - 2]
            return model.getCellHeight()
        }else {
            return 0.1
        }
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section >= 2 {
            let model = self.commentModels[section - 2]
            let commentHeader = MYGTopicFartherCommentsView.init()
            commentHeader.currentSection = section
            commentHeader.bindData(model)
            commentHeader.tapComonCallBack = {[weak self](comment,tsection) in
                self?.currentSection = tsection
                self?.writeTf.becomeFirstResponder()
                self?.isSubComment = true
                self?.currentCommentModel = comment
            }
            return commentHeader
        }
        
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return contentHeight
        }
        if indexPath.section == 1 {
            return 56
        }
      
        if indexPath.section >= 2 {
            let child = self.commentModels[indexPath.section - 2]
            if let replayArray = child.reply {
                let model = child.getAllReplyMoldes(replyArray: replayArray)[indexPath.row]
                return model.getCellHeight(isSub: true)
            }
            return UITableView.automaticDimension
            
        }
        return UITableView.automaticDimension
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "MYGTopicContentTableViewCell", for: indexPath) as! MYGTopicContentTableViewCell
            cell.selectionStyle = .none
            if self.model.id != 0 {
                cell.bindNewsData(self.model)
            }
            cell.getWebViewHeightCallback = { webHeight in
                self.contentHeight = webHeight
                self.table.reloadData()
            }
            return cell
        }else if indexPath.section == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MYGCommentCountCell", for: indexPath) as! MYGCommentCountCell
            cell.titleLB.text = "\(getAllReplyMoldes(replyArray: self.commentModels).count)" + "条评论"
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "MYGTopicCommentsTableViewCell", for: indexPath) as! MYGTopicCommentsTableViewCell
            cell.currentSection = indexPath.section
            
            let child = self.commentModels[indexPath.section - 2]
            if let replayArray = child.reply {
                let model =  child.getAllReplyMoldes(replyArray: replayArray)[indexPath.row]
                cell.bindData(model)
            }
            cell.tapComonCallBack = {[weak self](comment,section) in
                self?.currentSection = section
                self?.writeTf.becomeFirstResponder()
                self?.isSubComment = true
                self?.currentCommentModel = comment
            }
            return cell
        }
    }
}
